package com.newlink.building.userinfo.activity

import android.Manifest
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.newlink.building.library_rino.ConnectionController
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.event.CallCreateActionBean
import com.newlink.building.common_base.event.CallCreateBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_FAMILY
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_FAMILY
import com.newlink.building.common_base.event.TokenVo
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.FamilyManagementListData1
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityFamilyManagementDetailActivationBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_FamilyManagementDetailActivationPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_FamilyManagementDetailActivationContract
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub

/**
 * @author wangyang
 * @date 2022/10/11
 * @description 我的——家庭管理——已激活状态的详情页页面
 */
class Module_UserInfo_FamilyManagementDetailActivationActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_FamilyManagementDetailActivationContract.View, Module_UserInfo_FamilyManagementDetailActivationContract.Presenter>(),
    Module_UserInfo_FamilyManagementDetailActivationContract.View, View.OnClickListener {

    var data: FamilyManagementListData1? = null
    var localChannelName: String = ""
    var tokenVo: TokenVo? = null

    companion object {
        /**
         * 对外开放统一入口
         *
         * @param context
         * @param url     name
         * @param title   phone
         */
        fun startSelf(context: Context?, data: FamilyManagementListData1) {
            val intent = Intent(context, Module_UserInfo_FamilyManagementDetailActivationActivityNL::class.java)
            intent.putExtra("data", data)
            context?.startActivity(intent)
        }
    }

//    override fun attachLayoutRes(): Int = R.layout.activity_family_management_detail_activation

    private lateinit var mBinding: ActivityFamilyManagementDetailActivationBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityFamilyManagementDetailActivationBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        data = intent?.getSerializableExtra("data") as FamilyManagementListData1?
    }

    override fun initView() {
        super.initView()
        initCallErrorMessage()
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.family_management_detail_title)
        findViewById<ImageView>(R.id.iv_title_bar_right).setBackgroundResource(R.mipmap.title_bar_delete)
        if (isPrimaryAccount) {
            findViewById<ImageView>(R.id.iv_title_bar_right).visibility = View.VISIBLE
        } else {
            findViewById<ImageView>(R.id.iv_title_bar_right).visibility = View.GONE
        }
        findViewById<ImageView>(R.id.iv_title_bar_right).setOnClickListener(this)

//        Glide
//            .with(this)
//            .load(data?.picture)
//            .transform(MultiTransformation(CenterCrop(), CircleCrop()))
//            .placeholder(R.mipmap.family_management_head)
//            .into(iv_head)

        mBinding.tvName.text = data?.name
        mBinding.tvPhone.text = data?.aid.toString()
        mBinding.ivCall.setOnClickListener(this)
        coreContext.core.addListener(coreListener)


    }

    private val coreListener = object : CoreListenerStub() {
        override fun onCallStateChanged(
            core: Core,
            call: Call,
            state: Call.State,
            message: String,
        ) {
            when (state) {
                /**
                 * 由于在coreContext里OutgoingInit时会确保清除ChannelName,家庭成员呼叫是自己创建的ChannelName需要重新设置一下
                 */
                Call.State.OutgoingProgress -> {
                    if (localChannelName.isNotEmpty()) {
                        ConnectionController.getInstance(applicationContext)
                            .setRemoteChannelName(localChannelName)
                    }
                    if (tokenVo != null) {
                        ConnectionController.getInstance(applicationContext)
                            .convert2AgoraUserToken(tokenVo, agoraId, agoraAppId)
                    }
                }

                else -> {}
            }
        }
    }

    private fun initCallErrorMessage() {
        coreContext.callErrorMessageResourceId.observe(
            this
        ) {
            it.consume { message ->
                showSnackBar(message)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMsgReceived(event: MessageEvent) {
        when (event.msgType) {
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_FAMILY -> {
                data?.let {
                    val callCreateBean = event.msgContent as CallCreateBean?
                    localChannelName = callCreateBean?.data?.rtcToken?.channelName.orEmpty()
                    tokenVo = callCreateBean?.data
                    Module_Phone_VoipController.get().makeAudioCall(it.aid.toString(), it.name)
                }
            }
        }
    }

    fun sendCreateChannelEvent() {
        if (Module_Phone_VoipController.get().isCallingState()) {
            showToast(getString(R.string.outgoing_call_not_invite_again))
            return
        }
        val sipMsgEvent = MessageEvent(
            TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_FAMILY,
            CallCreateActionBean(aid = agoraId)
        )
        EventBus.getDefault().post(sipMsgEvent)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_call -> {
                //语音通话
                if (!PermissionHelper.required(this)
                        .hasPermission(Manifest.permission.RECORD_AUDIO)
                ) {
                    requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                } else {
                    sendCreateChannelEvent()
                }

            }

            R.id.iv_title_bar_right -> {
                //删除
                CustomDialog(this).setMessage(getString(R.string.family_management_delete))
                    .setPositiveButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            data?.id?.let {
                                NLog.e("[jake]..........删除家庭成员 ..serverType: ${userInfoData.prjType}")
//                                if (serverType == 1) {
                                mPresenter?.deleteFamilyManagement(accessToken, "$it")
//                                }else{
//                                    mPresenter?.deleteFamilyManagementFromKcp(accessToken, "$userId" , "$it" )
//                                }
                            }
                            dialog.dismiss()
                        }
                    }).setNegativeButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            dialog.dismiss()
                        }
                    }).show()
            }
        }
    }

    override fun createPresenter(): Module_UserInfo_FamilyManagementDetailActivationContract.Presenter =
        Module_UserInfo_FamilyManagementDetailActivationPresenter()

    override fun deleteFamilyManagementSuccess() {
        showToast(getString(R.string.default_delete_success))
        finish()
    }

    override fun deleteFamilyManagementFail() {
        showToast(getString(R.string.default_delete_fail))
    }

    override fun onDestroy() {
        super.onDestroy()
        coreContext.core.removeListener(coreListener)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            val granted =
                grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
            if (granted) {
                data?.id?.let { sendCreateChannelEvent() }
            } else {
                showPermissionDialog()

            }
        }
    }

    private fun showPermissionDialog() {
        val mDialog = DialogUtil.getConfirmDialog(
            this,
            getString(R.string.permission_content_audio),
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                }
            },
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {

                }
            }).show()
        mDialog.window?.run {
            attributes = attributes.apply {
                width = (windowManager.defaultDisplay.width * 0.95).toInt()
                gravity = Gravity.CENTER
            }
        }
    }
}